import { useEffect, useState } from 'react'
import NavHeader from './components/NavHeader.jsx'
import PageFooter from './components/PageFooter.jsx'
import { Layout, message } from 'antd'
import './css/App.css'
import RouteBefore from './router/RouteBefore.jsx'
import store from './redux/store.js'
import { Provider } from 'react-redux'
import LoginForm from './components/LoginForm.jsx'
import { getInfo, getUserById } from './api/user.js'
import { useDispatch } from 'react-redux'
import { initUserInfo, changeLoginStatus } from './redux/userSlice.js'
const { Header, Footer, Content } = Layout

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [messageApi, contextHolder] = message.useMessage()
  const dispatch = useDispatch()
  // 打开弹窗
  function loginHandle() {
    setIsModalOpen(true)
  }
  // 关闭弹窗
  const isModalClose = () => {
    setIsModalOpen(false)
  }

  useEffect(() => {
    const Token = localStorage.getItem('userToken')
    const fetchData = async () => {
      const res = await getInfo()
      if (res.data) {
        const result = await getUserById(res.data._id)
        dispatch(initUserInfo(result.data))
        dispatch(changeLoginStatus(true))
      } else {
        // 说明 token 过期了
        messageApi.warning(res.msg)
        localStorage.removeItem('userToken')
      }
    }
    if (Token) {
      fetchData()
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
  return (
    <Provider store={store}>
      <div className="App">
        {contextHolder}
        {/* 头部 */}
        <Header className="header">
          <NavHeader loginHandle={loginHandle} />
        </Header>
        {/* 匹配上的路由页面 */}
        <Content className="content">
          <RouteBefore />
        </Content>
        {/* 底部 */}
        <Footer className="footer">
          <PageFooter />
        </Footer>
        {/* 登录弹框 */}
        <LoginForm isModalOpen={isModalOpen} isModalClose={isModalClose} />
      </div>
    </Provider>
  )
}

export default App
